<template>
  <base-breadcrumb :title="titleName" :breadcrumb="!isAudit">
    <a-card :bordered="false">
      <title-name title="科技量化责任书信息"></title-name>
      <a-spin :spinning="loading">
        <a-form-model class="flex-model-form" ref="addForm" :model="form" :rules="rules">
          <a-row :gutter="24">

            <a-col :span="16">
              <a-form-model-item label="所属单位" prop="projectId">
                <org-tree-select is-need-auth isAllowNnect :disabled="eidtabled"
                                 v-model="form.projectId" :needTags="[]" @select="selectOrg">
                </org-tree-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="责任书年度">
                <BaseInput v-model="form.year" placeholder="请输入责任书年度" disabled></BaseInput>
              </a-form-model-item>
            </a-col>
          </a-row>
          <div>
            <a-button type="primary" v-if="curType !== 'look'" style="margin-bottom: 10px;"
                      @click="addIndexOpen" v-btnPermission="'ds_002_add_01'">添加指标项</a-button>
          </div>
          <s-table ref="tableSummary" table-layout="fixed" size="default" row-key="id"
                   :columns="columnsTotal" :data="loadData" bordered :alert="true" show-size-changer
                   show-quick-jumper :show-pagination="false" style="background: #fff"
                   @on-success="onSuccess">
            <template slot="passValue" slot-scope="text, record, index">
              <div
                   v-if="!eidtabled && record.refiningTypeName && !record.refiningTypeName.includes('加分项')">
                <div style="display: flex; align-items: center">
                  <BaseInputNumber :precision="record.quantizationTypeName.includes('百分比') ? 2 : 0"
                                   class="requiredFormItem" :min="0"
                                   v-model="form.detailsDTO[index].passValue"></BaseInputNumber>
                  <span style="margin-left: 5px"
                        v-if="record.quantizationTypeName">{{ record.quantizationTypeName.includes('百分比') ? '%' : '项' }}</span>
                </div>

              </div>
              <div
                   v-else-if="!eidtabled && record.refiningTypeName && !record.refiningTypeName.includes('个数') && record.refiningTypeName !== '加分项'">
                   <div style="display: flex; align-items: center">
                  <BaseInputNumber :precision="record.quantizationTypeName.includes('百分比') ? 2 : 0"
                                   class="requiredFormItem" :min="0"
                                   v-model="form.detailsDTO[index].passValue"></BaseInputNumber>
                  <span style="margin-left: 5px"
                        v-if="record.quantizationTypeName">{{ record.quantizationTypeName.includes('百分比') ? '%' : '项' }}</span>
                </div>
                
              </div>
              <span v-else>
                <span>{{ text }}</span>
                <span
                      v-if="text && record.quantizationTypeName && record.quantizationTypeName.includes('百分比')">%</span>
              </span>
            </template>
            <template slot="actualValue" slot-scope="text, record, index">
              <span>{{ text }}</span>
              <span
                    v-if="text && record.quantizationTypeName && record.quantizationTypeName.includes('百分比')">%</span>
            </template>
            <template slot="action" v-if="curType !== 'look'" slot-scope="text, record, index">
              <a-button type="link" @click="delData(record, index)">
                删除
              </a-button>
            </template>
          </s-table>
        </a-form-model>
      </a-spin>
    </a-card>
    <div v-if="!isConsultation" class="pub-header-btn page-btn-right-top">
      <!-- <a-button
        v-if="!eidtabled"
        :loading="DRAFTLoading"
        :disabled="loading"
        type="primary"
        @click="request(form.status === 'REJECTED' ? form.status : 'DRAFT')"
      >
        保存草稿
      </a-button> -->
      <a-button v-if="!eidtabled" :loading="SUBMITTEDLoading" :disabled="loading" type="primary"
                @click="submit">
        提交
      </a-button>
      <a-button v-checkVisibleInDetail @click="close"> 关闭 </a-button>
    </div>
    <selectApprover :businessId="newBusinessId" :processConfig="setProcessConfig"></selectApprover>
    <addIndex :visible="visible" @selectData="selectData" :addData.sync="addData"></addIndex>
  </base-breadcrumb>
</template>

<script>
import moment from 'moment'
import SelectSubCompany from '@/components/Select/SelectSubCompany.vue'
import SelectProject from '@/components/Select/SelectProject.vue'
import Api from '@/api/science/base/quantitativeResponsibilityLetter'
import addIndex from './addIndex'
import { addResponse, updateResponse, getResponseDetail } from '@/api/science/quantufiyResponse'
import { forEach } from 'lodash'
export default {
  name: 'a' + Date.now(),
  components: {
    SelectSubCompany,
    SelectProject,
    addIndex
  },
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },

  computed: {

    businessId() {
      return this.$route.query.businessId
    },
    isCom() {
      return this.$route.query.isCom == true || this.$route.query.isCom == 'true' || !!(this.businessId && !this.form.projectId)
    },
    levelTypeId() {
      return this.$route.query.levelTypeId
    },
    curType() {
      return this.$route.query.type
    },
    titleName() {
      const titleMap = {
        add: '新增科技量化责任书',
        edit: '编辑科技量化责任书',
        look: '科技量化责任书详情'
      }
      return titleMap[this.curType]
    },
    eidtabled() {
      return this.curType == 'look' || !!this.businessId
    }
    // columns() {
    //   return this.eidtabled ? this.columnsTotal : [...this.columnsTotal].slice(0, this.columnsTotal.length - 1)
    // }
  },
  data() {
    const columnsTotal = [
      {
        title: '提炼指标',
        dataIndex: 'refiningTypeName',
        width: '200px',
        customRender: (text, row, index) => {
          // this.$nextTick(() => {
          let rowSpan = 1
          if (index != 0 && text === this.simple[index - 1].refiningTypeName) {
            rowSpan = 0
            // 若不是，则往下合并与改行考核内容一致行的总行数
          } else {
            rowSpan = [...this.simple].filter(i => i.refiningTypeName == text).length
          }
          return {
            children: text,
            attrs: {
              rowSpan: rowSpan
            }
          }
          // })
        }
      },
      {
        title: '目标量化要求',
        dataIndex: 'demand'
      },
      {
        title: '目标要求值',
        width: '200px',
        dataIndex: 'passValue',
        scopedSlots: { customRender: 'passValue' }
      },
      {
        title: '实际完成值',
        width: '200px',
        dataIndex: 'actualValue',
        scopedSlots: { customRender: 'actualValue' }
      },
      {
        title: '操作',
        fixed: 'right',
        width: 220,
        scopedSlots: { customRender: 'action' }
      }
    ]
    // this.columnsTotal = columnsTotal
    return {
      visible: false,
      addData: [], //添加指标数据
      columnsTotal,
      orgName: '',
      validate: false,
      loading: false,
      SUBMITTEDLoading: false,
      DRAFTLoading: false,
      simple: [],
      validateList: [],
      loadData: () => {
        const param =
          this.curType == 'add'
            ? {
              needCount: false,
              query: {
                stop: 1,
                levelTypeId: this.levelTypeId
              }
            }
            : { id: this.$route.query.id }
        this.loading = true
        const api = this.curType == 'add' ? Api.queryList : getResponseDetail
        return api(param)
          .then(res => {
            this.loading = false
            if (res.code === 200) {
              const list = this.curType == 'add' ? this.addData : res.data.detailsVO
              this.simple = list || []
              this.form.detailsDTO = this.simple
              this.addData = this.simple
              this.validateList = this.simple.map(e => {
                const obj = {
                  id: e.id,
                  validate: false
                }
                return obj
              })
              let datas = {
                data: this.simple
              }
              if (this.curType !== 'add') {
                this.form.id = res.data.id
                this.form.orgId = res.data.orgId
                console.log('this.form.orgId', this.form.orgId)
                setTimeout(() => {
                  this.$nextTick(() => {
                    this.form.orgName = res.data.orgName.split('/')[0]
                    this.orgName = res.data.orgName;
                    this.form.projectId = res.data.projectId || res.data.orgId
                    this.form.projectName = res.data.projectName
                  })
                }, 300)
                this.form.year = res.data.year
                this.form.status = res.data.status
              }
              return datas
            } else {
              return false
            }
          })
          .catch(res => {
            this.loading = false
          })
      },
      form: {
        orgId: '',
        orgName: '',
        projectId: '',
        projectName: '',
        year: '',
        detailsDTO: []
      },
      rules: {
        orgId: [{ required: true, message: '请输选择分公司', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择项目', trigger: 'change' }]
        // activityTime: [
        //   { required: true, message: '请选择活动时间', trigger: 'change' },
        // ],
        // address: [
        //   { required: true, message: '请输入活动地点', trigger: 'blur' },
        // ],
        // contents: [
        //   { required: true, message: '请输入活动概要', trigger: 'blur' },
        // ],
      },
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      newBusinessId: null
    }
  },
  async mounted() {
    this.init()
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('QUANTIFIY_RESPONSE')
  },
  methods: {
    onSuccess() {
      this.$refs.tableSummary.localDataSource.sort(function (a, b) {
        return a.refiningTypeName < b.refiningTypeName ? -1 : 1
      })

    },
    //删除
    delData(data, index) {
      // this.addData = this.addData.filter(item => {
      //   return item.id !== data.id
      // })
      // this.$refs.tableSummary.loadData()
      this.$refs.tableSummary.localDataSource.splice(index, 1)
      this.addData = this.$refs.tableSummary.localDataSource
    },
    //打开指标模态框
    addIndexOpen() {
      this.visible = true
    },
    //选中指标
    selectData(val) {
      this.visible = false
      console.log('valvalval',val)
      if (val) {
        val.forEach(item=>{
          item.isNew = true
        })
        let [addData,newData] = [[],[...this.addData, ...val]]
        newData.forEach((item, index) => {
          let isE = addData.filter((v)=>v.id === item.id)
          if(isE.length === 0){
            addData.push(item);
          }
        })
        this.addData = addData
        this.addData.sort(function (a, b) {
          return a.refiningTypeName < b.refiningTypeName ? -1 : 1
        })
        this.form.detailsDTO = this.addData
        this.$refs.tableSummary.localDataSource = this.addData
        this.simple = this.addData
        // console.log('this.form.detailsDTOthis.form.detailsDTO',this.refs.tableSummary.loadData)
        // this.$refs.tableSummary.loadData()
      }
    },
    selectOrg(val) {
      if (val.length > 1) {
        this.form.orgName = val[val.length - 2].orgName
        this.form.orgId = val[val.length - 1].orgId
        this.form.projectName = val[val.length - 1].projectName
      }
      let orgName = []
      val.forEach(item => {
        orgName.push(item.orgName)
      })
      this.orgName = orgName.reduce((pre, item) => {
        return pre + '/' + item
      })
    },
    genID(length) {
      return Number(
        Math.random()
          .toString()
          .substr(3, length) + Date.now()
      ).toString(36)
    },
    orgChange(res) {
      this.form.orgName = res.orgName
    },
    projectChange(res) {
      this.form.projectName = res.name
    },
    init() {
      // this.queryList()
      if (this.curType === 'add') {
        this.form.year = moment().format('YYYY') + '年度'
      }
    },
    queryList() {
      const param = {
        needCount: false,
        query: {
          levelTypeId: this.levelTypeId
        }
      }
      this.loading = true
      Api.queryList(param)
        .then(res => {
          console.log(res)
          this.loading = false
          if (res.code == 200) {
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
    request(status) {
      const params = {
        ...this.form,
        status: status
      }
      params.detailsDTO?.forEach(item => {
        // if(item.quantizationTypeName.includes('百分比')){
        item.passValue = item.passValue?.toString()
        if(item.isNew) {
          delete item.id
        }
        // }
      })
      console.log('paramsparams', params)
      const text = status == 'SUBMITTED' ? '提交' : '保存'
      // const text = status == 'SUBMITTED' ? '提交' : '保存'
      const api = this.curType == 'add' ? addResponse : updateResponse
      const btnkey = status + 'Loading'
      this[btnkey] = true
      params.orgName = this.orgName
      if (!params.projectName) {
        delete params.projectId
        delete params.projectName
      }
      return api(params)
        .then(res => {
          this[btnkey] = false
          if (res.code == 200 || res.data.code == 200) {
            this.$message.success(text + '成功')
            this.close()
            if (status == 'SUBMITTED') {
              //提交时，返回id
              this.newBusinessId = res.data.id
              this.setProcessConfig = this.processConfig
              return
            } else {
              this.closeForm()
            }
          } else {
            this.$message.error(text + '失败！')
          }
        })
        .catch(() => {
          this[btnkey] = false
        })
    },
    submit() {
      const that = this
      that.setProcessConfig = null
      console.log('orgName', this.orgName);

      if (this.orgName === '西南公司') {
        this.$message.warn('请选择分公司或项目')
        return false
      }
      this.validateList = this.validateList.map(e => {
        e.validate = true
        return e
      })
      this.$refs.addForm.validate(valid => {
        if (valid) {
          const noInput = this.form.detailsDTO.filter(e => {
            return !e.refiningTypeName.includes('加分项') && !e.passValue
          })

          if (noInput.length > 0) {
            this.$message.warn('请填写完整！')
            return
          }
          this.submitApprovalConfirm(this.processConfig, flag => {
            if (!flag) {
              return
            }
            that.request('DRAFT')
          })
          // return new Promise((resolve, reject) => {
          //     const params = {
          //       ...that.form
          //     }
          //     const text = that.curType == 'add' ? '添加' : '编辑'
          //     const api = that.curType == 'add' ? addResponse : updateResponse
          //     that.SUBMITTEDLoading = true;
          //     api(params).then((res) => {
          //       if (res.code == 200) {
          //         that.$message.success(text+'成功')
          //         that.$close();
          //         resolve()
          //       } else {
          //         that.$message.error(text+'失败！')
          //         reject()
          //       }
          //     }).catch(() => {
          //       that.SUBMITTEDLoading = false;
          //       reject()
          //     })
          // })
        } else {
          console.log('error submit!!')
          this.$message.warning('信息不完整')
          return false
        }
      })
    },
    close() {
      if (this.businessId) {
        window.close()
        return
      }
      this.$router.push({
        path: '/science/quantitative',
        query: {
          isCom: this.isCom
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.flex-model-form .ant-form-item {
  display: flex;
}
</style>
